<template>
  <div class="flex justify-between">
    <div class="flex items-center gap-x-2" style="height: 30px">
      <img
        :src="NODE_ICON"
        class="w-6 h-6 rounded"
        alt="Start icon"
      />
      <div class="flex flex-col gap-y-1">
        <Input
          v-model="nodeLabel"
          v-if="showRename"
          @click.stop=""
          @on-enter="handleSetNodeName"
        >
          <template #suffix>
              <Icon type="md-checkmark" size="20" @click.prevent="handleSetNodeName" />
          </template>
        </Input>
        <p class="text-lg font-semibold text-black" v-else>
          {{ node?.node?.label || DEFAULT_NAME}}
        </p>
      </div>
    </div>
    <Dropdown>
      <Icon type="ios-more" />
        <template #list>
            <DropdownMenu>
                <DropdownItem @click.stop="handleRename">重命名</DropdownItem>
                <DropdownItem @click.stop="handleDeleteNode">删除</DropdownItem>
            </DropdownMenu>
        </template>
    </Dropdown>
  </div>
</template>
<script setup>
import { ref } from 'vue';
import { useVueFlow, useNode } from '@vue-flow/core';
import { Modal, Message } from 'view-ui-plus';
import { renameNode, deleteNode } from '@/api/modules/flow';

import { DEFAULT_NODES } from '../../lib/config';

const node = useNode();

// 默认节点名
const DEFAULT_NAME = DEFAULT_NODES[node.node.type].name;
const NODE_ICON = DEFAULT_NODES[node.node.type].icon;


const { removeNodes } = useVueFlow();
const nodeLabel = ref(node?.node?.label);
function handleDeleteNode() {
  Modal.confirm({
    mask: false,
    title: '警告',
    content: `<p>是否确认删除"${nodeLabel.value}"节点?</p>`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      // await deleteNode({
      //   data: { id: node.id },
      // });
      removeNodes([node.id]);
      Message.success('确认移除');
    },
  });
}
const showRename = ref(false);
function handleRename() {
  showRename.value = true;
}
async function handleSetNodeName () {
  const name = nodeLabel.value;
  if (name == node.node?.label) {
    showRename.value = false;
    return;
  };
  try {
    await renameNode({
      data: { id: node.id, nodename: name},
    });
    node.node.label = name;
    node.node.data.nodename = name;
  }finally {
    showRename.value = false;
  }
 
}
</script>
